package com.thprojects.myphotomemories.view;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;

import com.thprojects.imagefilters.Rotate;
import com.thprojects.myphotomemories.R;
import com.thprojects.myphotomemories.controller.FSController;
import com.thprojects.myphotomemories.controller.GuiController;
import com.thprojects.myphotomemories.model.Photo;

import exception.PhotoSourceNotFoundException;
import exception.SDNotReadyException;



public class RotatePhotoView extends Activity{
	FSController mFSController;
	Button mSave, mCancel;
	Photo mPhoto;
	Bitmap mBmp, mTmp;
	ImageView mImage;
	Rotate mRotation;
	ProgressDialog mPDialog;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.photo_rotate);
		
		Intent intent = getIntent();
        mPhoto = (Photo) intent.getParcelableExtra("photo");
        
        mFSController = FSController.getFSController(this);
        
        mImage = (ImageView)findViewById(R.id.photo_to_rotate);
        Display d = getWindowManager().getDefaultDisplay();
        try {
			mBmp = mFSController.decodeSampledBitmap(mPhoto.getPath(), d.getWidth(), d.getWidth());
			mImage.setImageBitmap(mBmp);
		} catch (PhotoSourceNotFoundException e) {
		} catch (SDNotReadyException e) {
		}
        
        mRotation = new Rotate();
        
        
        
        mSave = (Button)findViewById(R.id.save_rotated_photo);
        mSave.setOnClickListener(new OnClickListener() {	
			public void onClick(View v) {
				SavePhotoTask at = new SavePhotoTask();
		        at.execute();
			}
		});
        mCancel = (Button)findViewById(R.id.cancel_rotated_photo);
        mCancel.setOnClickListener(new OnClickListener() {	
			public void onClick(View v) {
				finish();
			}
		});
        
        mImage.setOnTouchListener(new OnTouchListener() {	
        	float firstX=0, firstY=0, firstAngle=0;
        	float cx = mImage.getWidth()/2;
        	float cy = mImage.getHeight()/2;
        	
        	public boolean onTouch(View v, MotionEvent event) {
        		//Log.d("MPM", "touched!, action="+event.getAction());
        		
				if (event.getAction() == MotionEvent.ACTION_DOWN){
					firstX = event.getX();
					firstY = event.getY();
					firstAngle = (float) Math.atan2(cy-firstY, cx-firstX);
					//Log.d("MPM", "first= ("+firstX+","+firstY);
				}
				else if (event.getAction() == MotionEvent.ACTION_UP){
					float lastX = event.getX();
					float lastY = event.getY();
					float lastAngle = (float) Math.atan2(cy-lastY, cx-lastX);
					//Log.d("MPM", "first= ("+firstX+","+firstY+"; last= ("+lastX+","+lastY);
					applyRotation(lastAngle>firstAngle);
				}
				return true;
			}
		});
	}
	
	private Bitmap applyRotation(boolean cw){
		mRotation.addRotation(cw ? +90f : -90f);
		Bitmap old = mTmp;
		mTmp = mRotation.apply(mBmp);
		mImage.setImageBitmap(mTmp);
		if (old!=null)old.recycle();
		return mBmp;
	}
	
	private class SavePhotoTask extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			Bitmap bmp = BitmapFactory.decodeFile(mPhoto.getPath());
			Bitmap old = bmp;
			
			bmp = mRotation.apply(bmp);
			
			old.recycle();
			
			try {
				mFSController.savePicture(bmp, mPhoto.getPath());
				finish();
			} catch (SDNotReadyException e) {
				GuiController.showError(RotatePhotoView.this, e.getMessage());
			}
			bmp.recycle();
			
			return null;
		}
	
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			mPDialog.dismiss();
		}
	
		@Override
		protected void onPreExecute() {
			mPDialog = ProgressDialog.show(RotatePhotoView.this, "", "Saving image. Please wait...", true);
		}
    	
    }
	
}
